import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import * as fs from 'node:fs'

// https://vitejs.dev/config/
export default defineConfig((configEnv) => {
  // 是否开发环境
  const isDev = configEnv.mode === 'development'
  const optimizeDepsElementPlusIncludes = ['element-plus/es']
  fs.readdirSync('node_modules/element-plus/es/components').map((dirname) => {
    fs.access(`node_modules/element-plus/es/components/${dirname}/style/css.mjs`, (err) => {
      if (!err) {
        optimizeDepsElementPlusIncludes.push(`element-plus/es/components/${dirname}/style/css`)
      }
    })
  })

  return {
    optimizeDeps: {
      //不要优化这些依赖项（必须是可解析的导入路径，不能是 glob）。
      // 这样可以避免 new dependencies optimized:
      // exclude: ['element-plus'],

      include: optimizeDepsElementPlusIncludes,
    },
    plugins: [
      vue(),
      // 自动导入
      AutoImport({
        dts: isDev ? './typing/auto.import.d.ts' : false,
        // dts: false,
        imports: [
          'vue',
          'vue-router',
          'pinia',
          '@vueuse/core',
          'vue-i18n',
          {
            from: 'vue-router',
            imports: ['RouteRecordRaw'],
            type: true,
          },
        ],
        resolvers: [ElementPlusResolver()],
        dirs: ['./src/**'],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler', // or 'modern'
        },
      },
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    build: {
      // 小于此阈值的导入或引用资源将内联为 base64 编码，以避免额外的 http 请求。设置为 0 可以完全禁用此项。
      assetsInlineLimit: 0,
    },
    esbuild: {
      // 只有生产环境不需要
      drop: !isDev ? ['console', 'debugger'] : undefined, // 删除 所有的console 和 debugger
    },
    server: {
      open: true,
      host: '0.0.0.0',
    },
  }
})
